package com.itljm.cxrMarket.task;

import com.itljm.cxrMarket.entity.Orders;
import com.itljm.cxrMarket.mapper.OrdersMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @author ljm
 * @date 2025/4/3 17:46
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderStatusUpdateService {
    private final OrdersMapper ordersMapper;

    // 每30分钟执行一次, 更新订单状态为待收货
    @Scheduled(cron = "0 */30 * * * ?")
    @Transactional
    public void updateShippingToWaitingReceive() {
        // 计算16小时前的时间点
        Date thresholdTime = new Date(System.currentTimeMillis() - 16 * 60 * 60 * 1000);

        List<Orders> shippingOrders = ordersMapper.findByStatusAndUpdateTimeBefore(2, thresholdTime);

        if (!shippingOrders.isEmpty()) {
            shippingOrders.forEach(order -> {
                ordersMapper.updateOrderStatus(order.getOrderId(), 3,new Date());
            });

            log.info("已更新 {} 个订单状态为待收货", shippingOrders.size());
        }else {
            log.info("没有符合条件的订单需要更新");
        }
    }
}
